// common/Components/voice.js
const innerAudioContext = wx.createInnerAudioContext()

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    voiceUrl: { // 属性名
      type: String, // 类型（必填），目前接受的类型包括：String, Number, Boolean, Object, Array, null（表示任意类型）
      value: '', // 属性初始值（可选），如果未指定则会根据类型选择一个
      observer: function (newVal, oldVal) {
        //获取语音时长
        innerAudioContext.src = newVal;
        //音频进入可以播放状态，但不保证后面可以流畅播放
        innerAudioContext.onCanplay(() => {
          console.log(innerAudioContext.duration)//0
        })
        setTimeout(() => {
          console.log(innerAudioContext.duration)//2.795102
          this.setData({
            voiceDuration: Math.ceil(innerAudioContext.duration)//向上取整
          })
        }, 1000)
      }
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    voiceDuration:'', //语音时长
    voiceIconName: '../../image/produce/voiceIcon1.png',
    playState: false, // 是否在播放 默认为false
  },
  
  pageLifetimes: {
    // 组件所在页面的生命周期函数
  },
  /**
   * 组件的方法列表
   */
  methods: {
    //播放语音 并添加动画
    playVocie: function () {
      var that = this;
      that.setData({
        playState: !that.data.playState
      })

      if (that.data.playState) {
        console.log('开始播放')
        that._voiceAnimation();
        innerAudioContext.src = that.data.voiceUrl;
        innerAudioContext.play();
      } else {
        console.log('暂停播放')
        that._voiceAnimationStop();
        innerAudioContext.stop();
      }
      // 播放结束
      innerAudioContext.onEnded((res) => {
        that._voiceAnimationStop();
      })
    },
    //帧动画
    _voiceAnimation:function(){
      var that = this;
        var i = 1;
        var index = 1;
        that.timer = setInterval(function () {
          i++;
          i = i % 3;
          that.setData({
            voiceIconName: '../../image/produce/voiceIcon' + i + '.png'
          })
        }, 500);
    },
    //帧动画
    _voiceAnimationStop: function () {
      var that = this;
      clearInterval(that.timer)//暂停话筒帧动画
        that.setData({
          voiceIconName: '../../image/produce/voiceIcon1.png'
        })
    }
  }
})
